package com.yby6.web.controller.tool;

import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.*;
import com.yby6.common.utils.uuid.UUID;
import com.yby6.framework.config.properties.QiniuOssProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import com.yby6.common.core.AjaxResult;
import com.yby6.framework.fastdfs.UploadService;

import java.io.*;

/**
 * @program: cmtc.ph2.backend
 * @ClassName: SignatureController
 * @create: 2022-05-18 13:15
 * @author: Yang Shuai
 * @since： JDK1.8
 * @SignatureController: 签章$
 **/


@RestController
@Slf4j
@RequestMapping("signature")
@RequiredArgsConstructor
public class SignatureController {

    private final QiniuOssProperties qiniuOssProperties;
    private final UploadService uploadService;

    /**
     * 签章
     *
     * @return
     */
    @RequestMapping(value = "signature", method = RequestMethod.POST)
    public AjaxResult signature (@RequestParam("files") MultipartFile[] files,
                                 @RequestParam("left") int left,
                                 @RequestParam("top") int top,
                                 @RequestParam("imgWidth") float imgWidth,
                                 @RequestParam("imgHeight") float imgHeight) {

        try {
            if (2 != files.length) {
                return AjaxResult.error("文件缺少请重新上传!");
            }
            long d1 = System.currentTimeMillis();

            MultipartFile pdf = null;
            MultipartFile signature = null;
            final String name = files[0].getOriginalFilename();

            boolean flag = name.indexOf(".pdf") != -1;
            if (flag) {
                pdf = files[0];
                signature = files[1];
            } else {
                pdf = files[1];
                signature = files[0];
            }


            File outFile = new File(UUID.fastUUID() + "-" + pdf.getOriginalFilename());

            FileOutputStream outputStream = new FileOutputStream(outFile);

            PdfReader reader = new PdfReader(pdf.getInputStream());
            PdfStamper stamper = new PdfStamper(reader, outputStream);
            // 将签名图片放在pdf文件的第4页
            PdfContentByte over = stamper.getOverContent(1);
            //签名图片
            Image contractSealImg = Image.getInstance(signature.getBytes());
            over.saveState();
            PdfGState pdfGState = new PdfGState();
            // 给图片设置透明度
            pdfGState.setFillOpacity(1F);
            over.setGState(pdfGState);

            // pdf 初始的宽度-高度
            float x = 794;
            float y = 842;

            // 图片宽度高度
            //imgWidth = imgHeight;
            //imgHeight = 43;

            // 前端传递
            float x1 = left - imgWidth + 50;
            float y1 = y - top - 23;
            // y1 -> 相当于前端的 bottom  设置图片位置
            log.info("坐标: {},{}", x1, y1);
            contractSealImg.setAbsolutePosition(x1, y1);
            // 设置图片大小 163 × 149
            contractSealImg.scaleAbsolute(imgWidth, imgHeight);
            // 将图片添加到pdf文件
            over.addImage(contractSealImg);
            over.restoreState();
            stamper.setFormFlattening(true);
            stamper.close();
            reader.close();
            outputStream.close();
            // 创建一个fileItem
            FileItem fileItem = createFileItem(outFile, outFile.getName());
            // 将文件转成 MultipartFile
            MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
            //上传文件到OSS
            final String s = uploadService.qiniuOssUploadFile(multipartFile);
            // 删除输出的文件
            outFile.delete();
            long d2 = System.currentTimeMillis();
            System.out.println("执行时间:" + (d2 - d1));
            return AjaxResult.success(s);
        } catch (Exception e) {
            log.error("签章异常:{0}", e);
            return AjaxResult.error(e.getMessage());
        }

    }

    /**
     * 创建FileItem
     *
     * @param file
     * @param fieldName
     * @return FileItem
     */
    private FileItem createFileItem (File file, String fieldName) {
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        FileItem item = factory.createItem(fieldName, "text/plain", true, file.getName());
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        FileInputStream fis = null;
        OutputStream os = null;
        try {
            fis = new FileInputStream(file);
            os = item.getOutputStream();
            while ((bytesRead = fis.read(buffer, 0, buffer.length)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            fis.close();
        } catch (IOException e) {
            log.error("createFileItem error :{}", e.getCause().getMessage());
        }
        return item;
    }

}
